#!/bin/bash

ROOTFS_ARCH=arm64
ROOTFS_CHIP=""
DEBIAN_VERSION=bullseye
HOST_NAME=HDC
DEFAULT_USER_NAME=vere

function umnt_wait()
{
    for i in {1..5}
    do
        # echo "umount $1 . #$i"
        sudo umount $1 &> /dev/null
        sleep 1
        if [ ! -d $1 ]; then 
            return 0
        else
            if (( $(ls -a $1 | wc -l) == 2)); then
                return 0
            fi
        fi
    done
    return 1
}

# 获取参数
for opt in $@; do
    case "$opt" in
        arch*)
            # 指定了CPU架构
            ROOTFS_ARCH=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        debian-version*)
            # 指定了debian版本
            DEBIAN_VERSION=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        host-name*)
            # 指定了主机名
            HOST_NAME=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        chip*)
            # 指定了芯片名称，也可以通过这个指定工控机的类型
            ROOTFS_CHIP=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        *) ;;
    esac
done

DEBIAN_URL=http://mirrors.ustc.edu.cn/debian
ROOTFS_PATH=fs_debian_${ROOTFS_ARCH}_${DEBIAN_VERSION}
ROOTFS_VERSION=$(cat customs/includes/boot/version)
PACKES=apt-transport-https,ca-certificates,locales,sudo
echo "I: ROOTFS_ARCH=$ROOTFS_ARCH DEBIAN_VERSION=$DEBIAN_VERSION ROOTFS_VERSION=$ROOTFS_VERSION HOST_NAME=$HOST_NAME CHIP=$ROOTFS_CHIP"

echo "I: 文件系统将保存在 $ROOTFS_PATH ."

if [ "$1" == "d" ]; then 
    sudo rm -rf $ROOTFS_PATH
fi

if [ ! -d $ROOTFS_PATH ]; then 
    sudo debootstrap --arch=$ROOTFS_ARCH --include=$PACKES --foreign $DEBIAN_VERSION $ROOTFS_PATH $DEBIAN_URL
fi

# 复制虚拟机文件到文件系统
sudo cp -af /usr/bin/qemu-arm-static $ROOTFS_PATH/usr/bin/

sudo rm -f $ROOTFS_PATH/etc/resolv.conf
sudo cp -f /etc/resolv.conf $ROOTFS_PATH/etc/resolv.conf

if [ ! -d $ROOTFS_PATH/customs ]; then 
    sudo mkdir $ROOTFS_PATH/customs
fi

sudo mount --bind customs $ROOTFS_PATH/customs
sudo chown -R root:root $ROOTFS_PATH/customs

# sudo cp -arf customs $ROOTFS_PATH/
# if [ -d $ROOTFS_PATH/debootstrap ]; then 
sudo chroot $ROOTFS_PATH/ /customs/init.sh $@
# fi

echo "I: 执行优化脚本"
sudo chroot $ROOTFS_PATH/ /customs/build.sh $@

if [ -f customs.tmp ]; then 
    sudo rm -f customs.tmp
fi

CUR_USER_NAME=$(id | awk -F ',' '{print$1}' | awk -F ' ' '{print$1}' | awk -F '(' '{print$2}' | awk -F ')' '{print$1}')
sudo chown -R $CUR_USER_NAME:$CUR_USER_NAME $ROOTFS_PATH/customs

# 记录本次的文件特征
for script in $(find customs/ -type f); do
    if [[ "$script" != *.tmp ]]; then
        echo "$(md5sum $script)" >> customs.tmp
    fi
done

# 卸载自定义操作文件夹
umnt_wait $ROOTFS_PATH/customs
reslut=$?
if (( $reslut == 0 )); then
    if [ -d $ROOTFS_PATH/customs ]; then 
        sudo rm -rf $ROOTFS_PATH/customs
    fi
else
    echo "E: 自定义操作文件夹卸载失败，无法继续进行。 $reslut"
    exit 1
fi
# echo "I: 更新文件系统版本"
# if [ -z $ROOTFS_VERSION ]; then 
#     # 文件系统版本未指定自动生成
#     ROOTFS_VERSION=$(date +$HOST_NAME-%Y%m%d)
# fi
# echo "$ROOTFS_VERSION" > version
# sudo mv -f version $ROOTFS_PATH/boot/version

